from pathlib import Path
import datetime as dt
import polars as pl

from fastapi import (
    FastAPI, 
    APIRouter,
    Depends,
    Body,
)

class FileMgrApi:
    def router():
        router = APIRouter(
            prefix = "/api/fileMgr",
            tags = ["文件管理"],
            responses = {404: {"description": "Not found"}},
        )
        
        @router.post("/queryWorkspace", 
                        summary="获取工作区目录信息")
        async def query_workspace(path:str = Body(...,embed=True)):
            success = False
            data = []
            msg = ""
            try:
                if path == "":
                    success = False
                    msg = "路径不能为空"
                elif not Path(path).exists():
                    success = False
                    msg = f"{path}: 路径不存在"
                else:
                    for f in Path(path).iterdir():
                        if f.is_dir():
                            data.append({
                                "name": f.name,
                                "isDir": True,
                                "path" : f.as_posix(),
                                "mtime": dt.datetime.fromtimestamp(f.stat().st_mtime).strftime("%Y-%m-%d %H:%M:%S"),
                            })
                        else:
                            data.append({
                                "name": f.name,
                                "isDir": False,
                                "path" : f.as_posix(),
                                "mtime": dt.datetime.fromtimestamp(f.stat().st_mtime).strftime("%Y-%m-%d %H:%M:%S"),
                            })
                    success = True
            except Exception as e:
                success = False
                msg = f"获取目录信息失败: {str(e)}"
                
            return {
                "success": success,
                "data": data,
                "msg": msg
            }

        @router.post("/readFileFieldList", 
                        summary="读取文件的表头")
        async def read_file_field_list(filePath:str = Body(...,embed=True)):
            success = False
            data = []
            msg = ""
            try:
                if not Path(filePath).exists():
                    success = False
                    msg = f"{filePath}: 路径不存在"
                else:
                    data = pl.scan_csv(filePath).collect_schema().names()
                    success = True
            except Exception as e:
                success = False
                msg = f"读取文件的表头: {str(e)}"
                
            return {
                "success": success,
                "data": data,
                "msg": msg
            }
        
        return router